#coding:utf-8
"""
*   Coder : Dzlua
*   Email : 505544956@qq.com
*   Time  : 2017/08/28
"""

#--------------------#
import os
import ftplib

#--------------------#
class FTP:
    ftp = ftplib.FTP()
    def __init__(self, host, port='21', pasv=True):
        self.ftp.set_pasv(pasv)
        self.ftp.connect(host, port)
    def login(self, user, pwd):
        self.ftp.login(user, pwd)
        print(self.ftp.welcome)
    def close(self):
        self.ftp.close()
    def ftpmkdirs(self, path, bfile=False):
        def _mkdirs(dir):
            dirs = dir.split('/')
            if len(dirs)<=1:
                return
            cur = '.'
            for d in dirs:
                cur += '/' + d
                try:
                    self.ftp.mkd(cur)
                except:
                    pass
        #
        pt = path
        if bfile:
            pt = path[0 : path.rfind('/')]
        _mkdirs(pt)
    def uploadfile(self, localfile, remotefile, callback=None):
        if os.path.isfile(localfile) == False:
            return False

        self.ftpmkdirs(remotefile, True)
        
        data = {
            'persize': 1024,
            'allsize': os.path.getsize(localfile),
            'localfile': localfile,
            'remotefile': remotefile,
            'times': 0,
            'size': 0,
            'finish': False
        }

        def funcallback(buf):
            if not callback:
                return
            data['buffer'] = buf
            data['size'] = data['size'] * data['times'] + len(buf)
            data['times'] += 1
            data['finish'] = (data['size'] >= data['allsize'])
            callback(data)

        file_handler = open(localfile, "rb", data['persize'])
        self.ftp.storbinary('STOR %s' % remotefile, file_handler, data['persize'], funcallback)
        file_handler.close()
        return True
#--------------------#
def callback(data):
    info = '%s-%s:%s/%s,finish:%s' % \
        ( data['persize'], data['times'], data['size'],
        data['allsize'], data['finish'] )
    print(info)
'''
ftp = FTP('192.168.10.239')
ftp.login('dzlua', '505544956')
ftp.uploadfile('/mnt/d/dzlua/python/ftp/ftp.py', 'a/b/ftp.py', callback)
ftp.close()
'''
ftp = FTP('120.27.13.210')
ftp.login('zh', '505544956')
ftp.uploadfile('/mnt/d/dzlua/python/ftp/ftp.py', 'a/b/ftp.py', callback)
ftp.close()
#--------------------#